<?php
namespace Admin\Controller;
use Think\Controller;

/**
* 定时检查需要做处理的数据，
*/
class FiveminController extends Controller{
	
	public function rongtest(){
		M('message')->where('max_del=1 AND min_del=1')->delete();
		M('message')->where('fa_id=0 AND max_del=1')->delete();
		$this->display();
	}
	public function index(){

		$now =intval(time());
		if($now < strtotime(date("Y-m-d 17:30")) && $now>strtotime(date("Y-m-d 7:30"))){
			$this->ajaxReturn(array('status'=>1,'次时间段内无操作'));
		}
		$dealModel = M('dealing');$activiModel = M('activity');$logModel = M('activity_log');
		//将时间过去的活动从处理列表中删除
		$dealModel->where('start_time<'.($now-3*60*60).' OR is_pay=0')->delete();
		//获取所有在18点到第二天早上6点的活动，
		$list = M('dealing')->select();

		foreach ($list as $key => $value) {
			if($value['is_pay'] == 0){
				$dealModel->where('activity_id='.$value['activity_id'])->delete();
				$activiModel->where('id='.$value['activity_id'])->delete();
			}
			//如果离开始还有半个小时，
			//判断是否已经发短信通知过，如果没有发消息通知，则自动发消息通知
			//比如，活动是6点开始，则在5点半到6点之间
			if($value['start_time'] > $now && $value['start_time'] < ($now + 15*60)){

				$activi = $activiModel->field('user_id,join_ed,bao_ed,is_remove')->where('id='.$value['activity_id'])->find();
				if(1 == $activi['is_remove']){
					$dealModel->where('activity_id='.$value['activity_id'])->delete();
					continue;
				}
				//检查是否已经发动通知消息，没有则发送通知消息
				if($value['fa_msg'] == 0){
					if($activi['join_ed'] > 0){
						$content = '您发起的活动即将开始，请及时到达确认签到';
						A('Message')->addSysMsg($user_id,$content,$value['activity_id']);
						$dealModel->where('activity='.$value['activity_id'])->save(array('fa_msg'=>1));
					}elseif($bao_ed > 0){
						$content = '您的活动将于15分钟后开始，请尽快选择报名者，否则活动将自动到期，届时仅退还见面礼，报名红包不予退还';
						A('Message')->addSysMsg($user_id,$content,$value['activity_id']);
						$dealModel->where('activity='.$value['activity_id'])->save(array('fa_msg'=>1));
					}
				}
				if($value['join_msg'] == 0){
					if($activi['join_ed'] > 0){
						$log_user = $logModel->where(array('activity_id'=>$value['activity_id'],'is_invited'=>2))->getField('user_id');
						$content = '您报名参与的活动即将开始，请及时到达确认签到';
						A('Message')->addSysMsg($log_user,$content,$value['activity_id']);
						$dealModel->where('activity='.$value['activity_id'])->save(array('join_msg'=>1));
					}
				}
			}

			//活动开始一个半小时之后，如果还没有到达，则爽约
			//比如现在是10点，活动开始时间是8点半
			if($value['start_time'] < ($now-90*60)){
				$activi = $activiModel->field('id,user_id,join_ed,bao_ed,start_time,status,is_arrive,join_money,bao_num,gift,is_remove')->where('id='.$value['activity_id'])->find();
				if(1 == $activi['is_remove']){
					$dealModel->where('activity_id='.$value['activity_id'])->delete();
					continue;
				}
				//如果进行了邀约，判断报名人是否爽约
				if($activi['join_ed'] > 0 && $activi['status'] != 9 && $activi['status'] != 11){
					$this->isFailJoin($activi);
				}
				if($activi['status'] == 9 || $activi['status'] == 11){
					$dealModel->where('activity_id='.$value['activity_id'])->delete();
				}
				
			//活动刚开始
			}elseif ($value['start_time'] < $now) {

				$activi = $activiModel->field('user_id,bao_ed,join_ed,id,bao_num,gift,join_money,status,is_remove')->where('id='.$value['activity_id'])->find();
				
				if($activi['join_ed'] == 0 && $value['dated'] == 0){

					$this->returnRedMoney($activi);
					$dealModel->where('activity_id='.$value['activity_id'])->delete();
				}
			}
		}
		
		$redList = M('red_money')->where('status=1 AND get_time<'.$now)->select();
		foreach ($redList as $k_r => $v_r) {
			$this->getRedMoney($v_r['id']);
		}
		$this->display();
	}

	public function getRedMoney($id){
		$redModel = M('red_money');
		$red = $redModel->where('id='.$id)->find();
		if (!$red || $red['status'] == 2) {
			return false;
		}
		$red_rate = M('admin_setting')->where('id=1')->getField('red_rate');
		$redModel->where('id='.$id)->save(array('status'=>2));
		$log_data = array(
			'user_id' 	=> $red['user_id'],
			'money'	 	=> ($red['money']*$red_rate),
			'add_time'	=> $red['get_time'],
			'type'		=> 104,
			'status'	=> 1,
			'activity_id'=> $red['activity_id'],
			'content'	=> '红包金额到账',
			'pay_type'	=> 3	
		);
		M('money_log')->add($log_data);
		M('user')->where('id='.$red['user_id'])->setInc('money',$red['money']);
		return true;
	}
	public function returnRedMoney($activity){
		//如果没有邀约
		if($activity['join_ed'] == 0 ){

			$is_dated = M('money_log')->where(array('activity_id'=>$activity['id'],'user_id'=>$activity['user_id'],'type'=>106))->find();

			if(!$is_dated){
				$resMoney = $activity['gift'] + ($activity['bao_num'] - $activity['bao_ed'])*$activity['join_money'];
				$moneyData = array(
					'money'		=> $resMoney,
					'user_id'	=> $activity['user_id'],
					'add_time'	=> time(),
					'type'		=> 106,
					'activity_id'	=> $activity['id'],
					'content'	=> '活动过期退款',
					'pay_type'	=> 3
				); 
				M('money_log')->add($moneyData);
				$content = '您发布的活动已过期，剩余的活动红包已返回您的钱包';
				A('Message')->addSysMsg($activity['user_id'],$content,$activity['id']);
				M('user')->where('id='.$activity['user_id'])->setInc('money',$resMoney);
				//M('dealing')->where('activity_id='.$activity['activity_id'])->save(array('dated'=>1));
			}
		}
	}

	//判断是否爽约
	public function isFailJoin($activi){
		if($activi['status'] == 11){
			return false;
		}
		$logModel = M('activity_log');
		//查找有没有邀约用户
		$logWhere = array('activity_id'=>$activi['id'],'is_invited'=>2);
		$actiLog = $logModel->where($logWhere)->select();

		if (!$actiLog && $activi['start_time'] < time()) {//如果没有邀约，则直接显示过期
			$actiModel->where('id='.$activi['id'])->save(array('status'=>0));
			return false;
		}
		if(!$actiLog){return false;}
		
		$status = $logData[0]['status'];
		if($status == 18 || $status == 16){
			return false;
		}
		$fail_join_this_activi = M('fail_join')->where('activity_id='.$activi['id'])->find();
		if($fail_join_this_activi){
			return false;
		}
		$impressModel = M('impress');
		//查找有没有用户被邀约了但是还没有判断是否邀约的
		if ($activi['start_time'] < (time()-90*60)) {
			//查看被邀约者状态，是否也是爽约
			//发起者爽约了
			if ($activi['status'] == 7 && $activi['is_arrive'] == 0) {
				//判断参与者是否也爽约
				foreach ($actiLog as $key => $value) {
					if($value['is_arrive'] == 0){ 
						//如果被邀约也爽约，退回报名红包,显示爽约
						$this->canFailJoin($activi,$value['user_id'],true);
						
						$money = (intval($activi['join_money']) * (intval($activi['bao_num']) - $activi['bao_ed']) + 1) + $activi['gift'] - 30;
						$this->returnHalfGift($activi['id'], $activi['user_id'], $money);
						//M('user')->where('id='.$activi['user_id'])->setInc('money',$money);

						$impress = $impressModel->where("user_id=".$value['user_id'])->find;
						if($impress){
							$impressModel->where("user_id=".$value['user_id'])->setInc('fail_join',1);
						}
						$content='由于您爽约，我们扣除了30元平台服务费，剩余没发出去的红包已退回您的钱包余额';
						A('Message')->addSysMsg($activi['user_id'],$content,$activi['id']);	
						break;
					} 

					$money = $activi['gift'] * 0.5;
					$this->addRedMoney($activi['id'], $value['user_id'], $money, time());

					//被邀约者没有爽约，3小时后获得50%见面礼红包，
					$money = $activi['gift'] * 0.5 + intval($activi['join_money']) * (intval($activi['bao_num']) - $activi['bao_ed']);
					$this->returnHalfGift($activi['id'], $activi['user_id'], $money);
					
					$content='由于您爽约，我们已将50%见面礼的金额作为诚意金，发给被邀约者。';
					A('Message')->addSysMsg($activi['user_id'],$content,$activi['id']);
					
				}
				$actiModel->where('id='.$activi['id'])->save(array('status'=>11));
			}
			if($activi['status'] == 13 && $activi['is_arrive'] == 1 && $actiLog[0]['is_arrive'] == 0){
				foreach ($actiLog as $key => $value) {
					
					$money = ($activi['join_money'] * ( 1 + $activi['bao_num'] - $activi['bao_ed'])) + $activi['gift'];
					$this->returnHalfGift($activi['id'], $activi['user_id'], $money);

					$res = $this->canFailJoin($activi,$value['user_id']);
					if($res == false)
						return false;

					$impress = $impressModel->where("user_id=".$value['user_id'])->find;
					if($impress){
						$impressModel->where("user_id=".$value['user_id'])->setInc('fail_join',1);
					}
				}
			}
			return true;
		}
		return false;
	}

	public function addRedMoney($activity_id,$user_id,$money,$start_time){
		//间隔时间
		$interval = 24*3600;
		//红包数据
		$data = array(
			'activity_id'=> $activity_id,
			'user_id' => $user_id,
			'money'	  => $money,
			'type'	  => 2,
			'status'  => 1,
			'add_time'=> time(),
			'content' => '发起者爽约支付一般诚意金',
			'get_time'=> $start_time + $interval,
		);
		$res = M('red_money')->add($data);
		return $res ? $res : false;
	}
	//参与人爽约活动
	public function canFailJoin($activi, $user_id, $flag = false){
		$logModel = M('activity_log');
		$logData = $logModel->where(array('activity'=>$activi['id'],'user_id'=>$user_id))->find();
		if($logData['status'] == 18 || $logData['is_arrive']){
			return false;
		}
		//将状态设置成违约
		$logModel->where('id='.$logData['id'])->save(array('status'=>18));
		M('red_money')->where(array('activity_id'=>$activi['id'],'user_id'=>$user_id))->save(array('status'=>-1));
        if(0 == $activi['is_arrive']){
        	return false;
        }
		//将用户暂时冻结
		$failData = array(
			'user_id' => $user_id,
			'add_time' => time(),
			'activity_id' => $activi['id'],
			'type'		=> 2,
			'year'		=> date('Y'),
			'yue'		=> date('m'),
		);
		M('fail_join')->add($failData);
		$failTimes = M('fail_join')->where(array('user_id'=>$user_id,'year'=>$failData['year'],'yue'=>$failData['yue']))->count();
		$exist_frize = M('frize')->where('user_id='.$user_id)->find();
		
		if ($failTimes >= 3) {
			if ($exist_frize) {
				M('frize')->where('id='.$exist_frize['id'])->save(array('status'=>2));
			}else{
				M('frize')->add(array('user_id'=>$user_id,'status'=>2));
			}
			$messageData = array(
				'fa_id'		=> 0,
				'shou_id'	=> $user_id,
				'content'	=> "由于本月已经爽约三次，账号已被永久冻结",
				'add_time'	=> time(),
				'type'		=> 0,
				'url'		=> ''
			);
			M('message')->add($messageData);
		}else{
			if ($exist_frize) {
				M('frize')->where('id='.$exist_frize['id'])->save(array('status'=>1));
			}else{
				M('frize')->add(array('user_id'=>$user_id,'status'=>1));
			}
			//通知用户支付诚意金
			A('Message')->sendPayChengyiMessage($user_id);
		}
	}

	/**
     * 发布者爽约，但是用户没有爽约，将一般见面礼作为诚意金支付给参与者，并返回剩下的一半给发起人
     * @access public
     * @param int $user_id 用户id
     * @param decimal $sum 返还的红包总金额
     * @param int $id 活动id
     * @param string $content 说明
     */
	public function addFailjoinChengyijing($id,$user_id,$activi_user,$money){
		$moneyArray[] = array(
			'user_id' => $user_id,
			'money'  => $money,
			'add_time' => time(),
			'activity_id' => $id,
			'type'		=> 109,
			'content'	=> '发起者爽约支付诚意金',
			'pay_type'	=> 3,
		);
		$moneyArray[] = array(
			'user_id' => $activi_user,
			'money'  => $money,
			'add_time' => time(),
			'activity_id' => $id,
			'type'		=> 105,
			'content'	=> '发起者爽约退回一半的见面礼',
			'pay_type'	=> 3,
		);
		M('money_log')->add($moneyArray);
		M('user')->where(array('id'=>$user_id))->setInc('money',$money);
		$res = M('user')->where(array('id'=>$activi_user))->setInc('money',$money);
		if($res === false){
			return false;
		}
		return true;
	}

    public function returnHalfGift($id, $user_id, $money){
		$moneyArray = array(
			'user_id' => $user_id,
			'money'  => $money,
			'add_time' => time(),
			'activity_id' => $id,
			'type'		=> 105,
			'content'	=> '爽约红包退回',
			'pay_type'	=> 3,
		);
		M('money_log')->add($moneyArray);
		M('user')->where(array('id'=>$user_id))->setInc('money',$money);
		M('dealing')->where(array('activity_id'=>$id))->delete();
    }

	/*活动已经开始了，
    *还没有人报名,活动过期
    *将用户的报名红包和见面礼红包返还给活动发起人
    */
    public function ReturnMoneyToDatedActivi($activity){
        $map = array(
            'user_id'       => $activity['user_id'],
            'activity_id'   => $activity['id'],
            'type'          => 106
        );
        $moneyLog = M('money_log')->where($map)->find();
        //活动已经开始了,并且没有报名,将用户的报名红包和见面礼红包还给本人
        if ($moneyLog) {
            //如果退款记录里面有
            $status = 0;$list=array();
        }else{
            $bao_num = $activity['bao_sum'];
            $money = $activity['bao_num'] * $activity['join_money'] + $activity['gift'];
            $redData = array(
                'money'=>$money,
                'user_id'=>$activity['user_id'],
                'activity_id'=>$activity['id'],
                'add_time'  => time(),
                'type'      => 106,
                'content'   => '未发放完的报名红包',
                'pay_type'  => 3
            );

            M('money_log')->add($redData);
            //通知用户他发起的活动已经过期，红包已经退回给他了
            $content = "您发布的活动已过期，报名红包已全额返回您的账户";
            $msg = array(
                'fa_id'     => 0,
                'shou_id'   => $activity['user_id'],
                'content'   => $content,
                'add_time'  => time(),
                'type'      => 0,
                'interval'  => intval(time()/(5*60))
            );
            M('message')->add($msg);
            A('message')->messageSystemList($activity['user_id'],$content,time());
            M('user')->where('id='.$activity['user_id'])->setInc('money',$money);
            $status = 0;$list=array();
        }
        return $status;
    }

    public function addFailJoinRecord($user_id){
    	$impressModel = M('impress');
    	$impress = $impressModel->where('user_id='.$user_id)->find();
    	if($impress){
    		$impressModel->where('user_id='.$user_id)->setInc('fail_join',1);
    	}
    }
}